<template>
  <div class="yt-table-group">
    <el-table
        border
        class="yt-table"
        @selection-change="selectionChange"
        :data="tableData"
        @cell-mouse-enter="cellMouseEnter"
        @cell-mouse-leave="cellMouseLeave"
        style="width: 100%"
        :max-height="maxHeight || '500px'"
        ref="table">
      <el-table-column v-if="isSelection" type="selection" width="55"></el-table-column>
      <el-table-column v-if="isIndex" label="序号" type="index" align="center" width="60" show-overflow-tooltip>
        <template slot-scope="{ row,$index }">
          {{ (currentPage-1) * pageSize + ($index+1)}}
        </template>
      </el-table-column>
      <el-table-column
          v-for="(item, index) in tableHeader"
          :key="index"
          :prop="item.prop"
          :label="item.name"
          :sortable="item.sortable ? item.sortable : false"
          :width="parseString(item.width)"
          :min-width="item.minWidth"
          :align="item.align||'center'"
          :fixed="item.fixed"
          :show-overflow-tooltip="item.tooltip||false">
        <template slot-scope="{ row }">
          <span v-if="item.button" :class="{ show: row.isHover, hidden: !row.isHover }">
            <slot name="operation" :data="row"></slot>
          </span>

          <slot v-else-if="item.slot" name="operation" :data="row"></slot>

          <slot v-else-if="item.tag" :name="item.prop" :data="row"></slot>

          <span
              v-else
              :class="{ show: !row.isHover, hidden: row.isHover && item.button }"
              v-html="
              item.formatter
                ? item.formatter(row, item.prop, row[item.prop], index)
                : (row[item.prop] || '--')"></span>
        </template>
      </el-table-column>
    </el-table>
    <div class="boot" v-if="pgTotalNum">
      <div>
        <el-button
            size="mini"
            type="primary"
            @click="printTab">
          <i class="el-icon-printer"></i>
        </el-button>
        <el-button
            size="mini"
            type="primary"
            @click="exportExcel">
          <i class="el-icon-download"></i>
        </el-button>

        <slot name="delbtn"></slot>
      </div>
      <el-pagination
          class="yt-pagination"
          background
          v-if="pgVisible"
          :layout="pgType"
          :page-sizes="pgSize"
          :current-page.sync="currentPage"
          :page-size.sync="pageSize"
          :total="pgTotalNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
      </el-pagination>
    </div>
  </div>
</template>
<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";

export default {
  props: {
    tableHeader: {
      type: Array,
      default: () => [],
    },
    tableData: {
      type: Array,
      default: () => [],
    },
    //selection（多选）/index（索引）/expand(扩展按钮)/none(单选)
    isSelection: {
      type: Boolean,
      default: false,
    },
    height: {
      type: String,
      default: "auto",
    },
    maxHeight: {
      type: String,
      default: "500px",
    },
    pgVisible: {
      type: Boolean,
      default: true,
    },
    pgType: {
      type: String,
      default: "total, sizes, prev, pager, next, jumper",
    },
    pgTotalNum: {
      type: Number,
      default: 0,
    },
    pgSize: {
      type: Array,
      default: () => [10, 20, 30, 40],
    },
    isIndex: {
      type: Boolean,
      default: true,
    },
    page: {
      type: Number,
      default: 1,
    },
    limit: {
      type: Number,
      default: 10,
    },
  },
  data() {
    return {};
  },
  computed: {
    currentPage: {
      get() {
        return this.page
      },
      set(val) {
        this.$emit('update:page', val)
      }
    },
    pageSize: {
      get() {
        return this.limit
      },
      set(val) {
        this.$emit('update:limit', val)
      }
    }
  },
  created() {
  },
  mounted() {

  },
  methods: {
    printTab() {
      this.printHTML()
    },
    selectionChange(val) {
      console.log(val);
    },
    /**
     * 将参数val转换魏字符串
     * @param val
     * @returns {string}
     */
    parseString(val) {
      if (val) {
        return String(val);
      } else {
        return "";
      }
    },
    // 导出
    exportExcel() {
      let wb = XLSX.utils.table_to_book(this.$refs.table.$el);
      let wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], {type: "application/octet-stream"}),
          "表格.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    /**
     * table表格行鼠标移入事件
     * @param row
     * @param column
     * @param cell
     * @param event
     */
    cellMouseEnter(row, column, cell, event) {
      row.isHover = true;
    },
    /**
     * table表格行鼠标移出事件
     * @param row
     * @param column
     * @param cell
     * @param event
     */
    cellMouseLeave(row, column, cell, event) {
      row.isHover = false;
    },
    handleSizeChange(val) {
      this.$emit("handleSizeChange", val);
      this.$emit('pagination', {page: this.currentPage, limit: val})
    },
    handleCurrentChange(val) {
      this.$emit("handleCurrentChange", val);
      this.$emit('pagination', {page: val, limit: this.pageSize})
    },

    // handleSizeChange (val) {
    //   this.$emit('pagination', {page: this.currentPage, limit: val})
    //   if (this.autoScroll) {
    //     scrollTo(0, 800)
    //   }
    // },
    // handleCurrentChange (val) {
    //   this.$emit('pagination', {page: val, limit: this.pageSize})
    //   if (this.autoScroll) {
    //     scrollTo(0, 800)
    //   }
    // }
    // 导出
    exportFile() {
      const tHeader = this.getTHeader()
      const filterVal = this.getFilterVal()
      import('../js/Export2Excel').then(excel => {
        const list = this.data
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.title || +new Date(),
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    getTHeader() {
      let arr = []
      this.tableHeader.forEach(item => {
        if (item.prop) {
          arr.push(item.name)
        }
      })
      return arr
    },
    getFilterVal() {
      let arr = []
      this.tableHeader.forEach(item => {
        if (item.prop) {
          arr.push(item.prop)
        }
      })
      return arr
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    // 打印
    printHTML() {
      const tHeader = this.getTHeader()
      const filterVal = this.getFilterVal()
      let tableHtml = `<table  width="100%"  align="center" cellspacing="0" border="1" style="border-collapse:collapse"><thead><tr align="center">`
      let tableHead = ``
      tHeader.forEach(item => {
        tableHead += `<th style="padding: 6px 8px;min-width: 100px">${item}</th>`
      })
      tableHead += '</tr></thead>'
      let tlementType = '<tbody>'
      this.tableData.forEach((item) => {
        tlementType += '<tr align="center" >'
        filterVal.forEach((aitem) => {
          tlementType += `<td  style="padding: 6px 8px">${item[aitem]}</td>`
        })
        tlementType += `</tr>`
      })
      tlementType += `</tbody>`
      let printDom = tableHtml + tableHead + tlementType + '</table>'
      let h = window.open('打印窗口', '_blank')
      h.document.write(printDom)
      h.document.close()
      h.print()
      h.close()
    }
  },
};
</script>
<style lang="less" scoped>
  .boot {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 5px 0;
  }

  .yt-table-group {
    /deep/ .el-table th.el-table__cell > .cell {
      text-align: center !important;
      padding: 0 !important;
    }

    /deep/ .el-table td.el-table__cell div {
      /*text-align: center;*/
      /*display: flex;*/
      /*justify-content: center;*/
    }

    /deep/ .el-table {
      position: relative;

      thead tr {
        background-color: rgba(255, 255, 255, 0.3) !important;

        th {
          padding: 8px 0 !important;

          .cell {
            /*font-size: 14px;*/
          }
        }
      }
    }

    /deep/ .cell {
      span {
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
    }

    /deep/ .el-table--border .el-table__cell,
    .el-table__body-wrapper
    .el-table--border.is-scrolling-left
    ~ .el-table__fixed {
      /*border-right: none;*/
    }

    .el-pagination {
      position: relative;
      white-space: nowrap;
      padding: 10px 10px;
      font-weight: 700;

      /deep/ .el-pagination__total {
        color: #ffffff;
      }

      /deep/ .el-pagination__jump {
        color: #ffffff;
      }
    }

    .show {
      display: inline;
    }

    .hidden {
      display: none;
    }
  }
</style>
